package com.pansoft.openplanet.activity.child;

import android.app.AlertDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.util.EnvSupportManager;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.account.model.ActGeneratorBean;
import com.pansoft.openplanet.account.model.BchGeneratorBean;
import com.pansoft.openplanet.account.model.BtcBean;
import com.pansoft.openplanet.account.model.EthBean;
import com.pansoft.openplanet.account.util.ActAccountGenerator;
import com.pansoft.openplanet.account.util.BTCAccountGenerator;
import com.pansoft.openplanet.account.util.BchAccountGenerator;
import com.pansoft.openplanet.account.util.EthAccountGenerator;
import com.pansoft.openplanet.activity.TCBaseActivity;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.constant.TalkChainConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.util.TCAccountManager;
import com.pansoft.openplanet.widget.TCLoadingDataView;
import com.utilcode.util.TimeUtils;
import com.utilcode.util.ToastUtils;

import java.io.File;

import io.reactivex.disposables.Disposable;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * Created by will on 18-3-27.
 */

public class ChildRestoreByMnemonicFragment extends BaseFragment implements View.OnClickListener {

    private static final String TAG = "RestoreByMnemonicFragment";
    private String imUserId, number, menonic;
    private EditText editText1, editText2, editText3, editText4, editText5, editText6,
            editText7, editText8, editText9, editText10, editText11, editText12;

    private AccountDao accountDao;
    //默认存放keysTORE的 文件夹
    private String basePath;
    private Account account;
    private String avatar;
    private String walletAvatar;
    private String walletName;
    private int chainId;//钱包类型
    private String secretWord;//加密的助记词
    private TCAccountManager tcAccountManager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.talk_chain_fragment_verify_token, null);

        number = getActivity().getIntent().getExtras().getString("number");
        avatar = getActivity().getIntent().getStringExtra("avatar");
        walletAvatar = getActivity().getIntent().getStringExtra("wallet_avatar");
        walletName = getActivity().getIntent().getStringExtra("wallet_name");
        chainId = getActivity().getIntent().getIntExtra("chainId", IPAssetsConstant.CHAIN_ID_TURBOCHAIN);

        editText1 = view.findViewById(R.id.et_1);
        editText2 = view.findViewById(R.id.et_2);
        editText3 = view.findViewById(R.id.et_3);
        editText4 = view.findViewById(R.id.et_4);
        editText5 = view.findViewById(R.id.et_5);
        editText6 = view.findViewById(R.id.et_6);
        editText7 = view.findViewById(R.id.et_7);
        editText8 = view.findViewById(R.id.et_8);
        editText9 = view.findViewById(R.id.et_9);
        editText10 = view.findViewById(R.id.et_10);
        editText11 = view.findViewById(R.id.et_11);
        editText12 = view.findViewById(R.id.et_12);
        Button tvNext = view.findViewById(R.id.tv_next);
        tvNext.setOnClickListener(this);

        accountDao = new AccountDao(getActivity());
        tcAccountManager = new TCAccountManager(getActivity());

        basePath = TalkChainConstant.getChildAccountFilePath(getActivity()) + File.separator + number;
        return view;

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tv_next) {
            verifyMnemonic();

        }
    }

    private void verifyMnemonic() {

        if (editText1.getText().toString().equals("") || editText2.getText().toString().equals("")
                || editText3.getText().toString().equals("") || editText4.getText().toString().equals("")
                || editText5.getText().toString().equals("") || editText6.getText().toString().equals("")
                || editText7.getText().toString().equals("") || editText8.getText().toString().equals("")
                || editText9.getText().toString().equals("") || editText10.getText().toString().equals("")
                || editText11.getText().toString().equals("") || editText12.getText().toString().equals("")) {
            ToastUtils.showShort(R.string.open_planet_incomplete_mnemonic_hint);
        } else {
            if (EnvironmentVariable.getPassword() == null || "".equals(EnvironmentVariable.getPassword())) {
                ToastUtils.showShort(R.string.open_planet_password_not_exist_hint);
                return;
            }

            StringBuilder stringBuilder = new StringBuilder();
            menonic = stringBuilder.append(editText1.getText().toString())
                    .append(" ")
                    .append(editText2.getText().toString())
                    .append(" ")
                    .append(editText3.getText().toString())
                    .append(" ")
                    .append(editText4.getText().toString())
                    .append(" ")
                    .append(editText5.getText().toString())
                    .append(" ")
                    .append(editText6.getText().toString())
                    .append(" ")
                    .append(editText7.getText().toString())
                    .append(" ")
                    .append(editText8.getText().toString())
                    .append(" ")
                    .append(editText9.getText().toString())
                    .append(" ")
                    .append(editText10.getText().toString())
                    .append(" ")
                    .append(editText11.getText().toString())
                    .append(" ")
                    .append(editText12.getText().toString())
                    .toString();

            account = new Account();
            //accountDao.deleteByCurentImuserId();
            TCLoadingDataView.show(getContext(), R.string.open_planet_recovering);
            if (chainId == IPAssetsConstant.CHAIN_ID_BTC) {
                restoreBTCWallet();
                return;
            } else if (chainId == IPAssetsConstant.CHAIN_ID_ETH) {
                restoreETHWallet(IPAssetsConstant.ChainEnum.ETH);
            }else if (chainId == IPAssetsConstant.CHAIN_ID_ETE) {
                restoreETHWallet(IPAssetsConstant.ChainEnum.ETE);
            } else if (chainId == IPAssetsConstant.CHAIN_ID_ACT) {
                restoreACTWallet();
            } else if (chainId == IPAssetsConstant.CHAIN_ID_BCH) {
                //恢复bch钱包
                restoreBchWallet();
            }

        }
    }

    /**
     * 恢复btc钱包
     */
    private void restoreBTCWallet() {
        Disposable disposable = BTCAccountGenerator.recoverBtcAccountByMnemoric(basePath, menonic, new BTCAccountGenerator.GeneratorListener() {
            @Override
            public void generatorSuccess(BtcBean btcBean) {
                Account dbAccout = accountDao.getAccount(btcBean.getBtcAddress());
                if (dbAccout != null && dbAccout.isEnable()) {
                //if (accountDao.getAccount(btcBean.getBtcAddress()) != null) {
                    //账户已存在
                    TCLoadingDataView.dismiss();
                    showCoverAlertDialog();
                    return;
                } else {
                    if (EnvSupportManager.isSupportHDWallet()) {
                        account.setHdBtcXpub(btcBean.getHdBtcXpub());
                        account.setHdBtcMaxChildIndex(btcBean.getHdBtcMaxChildIndex());
                        account.setHdBtcCurrentChildAddress(btcBean.getHdBtcCurrentChildAddress());
                    }
                    account.setAddress(btcBean.getBtcAddress());
                    account.setAccountAvatar(walletAvatar);
                    account.setAcccountName(walletName);
                    account.setFileName(btcBean.getKeyStoreFilePath());
                    account.setImUserId(EnvironmentVariable.getProperty(CHAT_USER_ID));
                    account.setPublicKey(btcBean.getBtcPubKey());
                    account.setSecretMnemonic(btcBean.getSecretMnemonic());
//                    account.setSecretPrivateKey(btcBean.getBtcPrivKey());
                    account.setMainAccoutAddress(EnvironmentVariable.getProperty("tc_ethAddress", ""));
                    account.setBlockChainName(IPAssetsConstant.ChainEnum.BTC.chainName);
                    account.setCreateTime(TimeUtils.getNowString());
                    // account.setEnable(true);
                    accountDao.insertOrReplace(account);

                    addChildToServer(btcBean.getBtcAddress(), btcBean.getBtcPubKey(), btcBean.getBtcPrivKey());

                }
            }

            @Override
            public void generatorFail() {
                TCLoadingDataView.dismiss();
                ToastUtils.showShort(R.string.open_planet_recovering_fail_check_mnemonic);
            }
        });
        ((TCBaseActivity) getActivity()).addDisposable(disposable);
    }

    /**
     * 恢复bch钱包
     */
    private void restoreBchWallet() {
        Disposable disposable = BchAccountGenerator.recoverBchAccountByMnemoric(basePath, menonic, new
                BchAccountGenerator.GeneratorListener() {
                    @Override
                    public void generatorSuccess(BchGeneratorBean bchBean) {
                        Account dbAccout = accountDao.getAccount(bchBean.getWalletAddress());
                        if (dbAccout != null && dbAccout.isEnable()) {
                            //if (accountDao.getAccount(btcBean.getBtcAddress()) != null) {
                            //账户已存在
                            TCLoadingDataView.dismiss();
                            showCoverAlertDialog();
                            return;
                        } else {
                            account.setAddress(bchBean.getWalletAddress());
                            account.setAccountAvatar(walletAvatar);
                            account.setAcccountName(walletName);
                            account.setFileName(bchBean.getKeyStoreFilePath());
                            account.setImUserId(EnvironmentVariable.getProperty(CHAT_USER_ID));
                            account.setPublicKey(bchBean.getPublicKey());
                            account.setSecretMnemonic(bchBean.getSecretMnemonic());
//                    account.setSecretPrivateKey(btcBean.getBtcPrivKey());
                            account.setMainAccoutAddress(EnvironmentVariable.getProperty("tc_ethAddress", ""));
                            account.setBlockChainName(IPAssetsConstant.ChainEnum.BCH.chainName);
                            account.setCreateTime(TimeUtils.getNowString());
                            // account.setEnable(true);
                            accountDao.insertOrReplace(account);

                            addChildToServer(bchBean.getWalletAddress(), bchBean.getPublicKey(), bchBean.getPrivateKey());

                        }
                    }

                    @Override
                    public void generatorFail() {
                        TCLoadingDataView.dismiss();
                        ToastUtils.showShort(R.string.open_planet_recovering_fail);
                    }
                });
        ((TCBaseActivity) getActivity()).addDisposable(disposable);
    }

    private void restoreETHWallet(final IPAssetsConstant.ChainEnum chainEnum) {
        Disposable disposable = EthAccountGenerator.recoverAccountByMnemoric(basePath, menonic,chainEnum,
                new EthAccountGenerator.GeneratorListener() {
                    @Override
                    public void generatorSuccess(EthBean ethBean) {
                        Account dbAccout = accountDao.getAccount(ethBean.getEthAddress());
                        if (dbAccout != null && dbAccout.isEnable()) {
                       // if (accountDao.getAccount(ethBean.getEthAddress().toLowerCase()) != null) {
                            //账户已存在
                            TCLoadingDataView.dismiss();
                            showCoverAlertDialog();
                            return;
                        } else {
                            account.setAddress(ethBean.getEthAddress());
                            account.setAccountAvatar(walletAvatar);
                            account.setAcccountName(walletName);
                            account.setFileName(ethBean.getKeyStoreFilePath());
                            account.setImUserId(EnvironmentVariable.getProperty(CHAT_USER_ID));
                            account.setPublicKey(ethBean.getEcKeyPair().getPublicKey().toString());
                            account.setMaster(false);
                            account.setCurrentShow(false);
                            account.setBlockChainName(chainEnum.chainName);
                            account.setMainAccoutAddress(EnvironmentVariable.getProperty("tc_ethAddress", ""));
                            // account.setEnable(true);
                            accountDao.insertOrReplace(account);

                            String publicKey = ethBean.getEcKeyPair().getPublicKey().toString();
                            String privateKey = ethBean.getEcKeyPair().getPrivateKey().toString();

                            addChildToServer(ethBean.getEthAddress(), publicKey, privateKey);
                        }

                    }

                    @Override
                    public void generatorFail() {
                        TCLoadingDataView.dismiss();
                        ToastUtils.showShort(R.string.open_planet_recovering_fail);
                    }
                });


        ((TCBaseActivity) getActivity()).addDisposable(disposable);
    }

    private void restoreACTWallet() {
        Disposable disposable = ActAccountGenerator.recoverAccountByMnemoric(menonic, new ActAccountGenerator.GeneratorListener() {
            @Override
            public void generatorSuccess(ActGeneratorBean actGeneratorBean) {
                Account dbAccout = accountDao.getAccount(actGeneratorBean.getWalletAddress());
                if (dbAccout != null && dbAccout.isEnable()) {
                    //账户重复
                    TCLoadingDataView.dismiss();
                    showCoverAlertDialog();
                    return;
                }

                account.setAddress(actGeneratorBean.getWalletAddress());
                account.setAccountAvatar(walletAvatar);
                account.setAcccountName(walletName);
                account.setImUserId(EnvironmentVariable.getProperty(CHAT_USER_ID));
                account.setPublicKey(actGeneratorBean.getPublicKey());
                account.setSecretPrivateKey(actGeneratorBean.getSecretPriKey());
                account.setMaster(false);
                account.setCurrentShow(false);
                account.setMainAccoutAddress(EnvironmentVariable.getProperty("tc_ethAddress", ""));
                //account.setEnable(true);
                account.setBlockChainName(IPAssetsConstant.ChainEnum.ACHAIN.chainName);
                accountDao.insertOrReplace(account);
                addChildToServer(actGeneratorBean.getWalletAddress(), actGeneratorBean.getPublicKey(), actGeneratorBean.getPrivateKey());
            }

            @Override
            public void generatorFail() {
                TCLoadingDataView.dismiss();
                ToastUtils.showShort(R.string.open_planet_recovering_fail);
            }
        });


        ((TCBaseActivity) getActivity()).addDisposable(disposable);
    }

    private void addChildToServer(String address, String publicKey, String privateKey) {
        String blockChainName = account.getBlockChainName();
        if (chainId == IPAssetsConstant.CHAIN_ID_BTC || chainId == IPAssetsConstant.CHAIN_ID_BCH) {
            //btc
//            blockChainName = IPAssetsConstant.ChainEnum.BTC.chainName;
            secretWord = account.getSecretMnemonic();
        }

        tcAccountManager.addChildHdBtcWallet(publicKey, privateKey, address, walletAvatar, walletName
                , blockChainName, secretWord, account.getHdBtcXpub(),
                new TCAccountManager.AccountManagerListener<String>() {
                    @Override
                    public void onSuccess(String object) {
                        TCLoadingDataView.dismiss();
                        //恢复成功，更改状态为可用
                        if (account != null) {
                            account.setEnable(true);
                            accountDao.insertOrReplace(account);
                        }

                        ToastUtils.showShort(R.string.open_planet_recovering_success);
                        getActivity().finishAffinity();
                    }

                    @Override
                    public void onFail(String fail) {
                        TCLoadingDataView.dismiss();
                        showFailAlert(null);
                    }
                });
    }

    private void showFailAlert(String message) {
        if (message == null)
            message = ResStringUtil.getString(R.string.open_planet_recovering_fail_retry);
        new AlertDialog.Builder(getActivity())
                .setTitle(R.string.common_text_hint)
                .setMessage(message)
                .setPositiveButton(ResStringUtil.getString(R.string.common_text_confirm), null)
                .create()
                .show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ((TCBaseActivity) getActivity()).dispose();
    }

    /**
     * 提示是否覆盖的
     */
    private void showCoverAlertDialog() {
        new AlertDialog.Builder(getActivity())
                .setTitle(R.string.common_text_hint)
                .setMessage(ResStringUtil.getString(R.string.open_planet_import_wallet_exist))
                .setPositiveButton(ResStringUtil.getString(R.string.common_text_confirm), null)
                .create()
                .show();
    }
}
